package com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.Impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sxfq.loansupermarket.backsystem.GunsApplication;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.IntegralMallLoginService;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ScoreDealInfo;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.VipLevelInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.CaseInfo;
import com.sxfq.loansupermarket.backsystem.modular.doctorLooked.entity.ToothSite;
import com.sxfq.loansupermarket.backsystem.modular.guestDimension.entity.GuestDimensionInfo;
import com.sxfq.loansupermarket.backsystem.modular.guestDimension.service.IGuestDimensionService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.websocket.WebSocketWxChat;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.WebChatConfig;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.WebChatUtil;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.SatisfactionSurvey;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.WechatUserInfoEntity;
import com.sxfq.loansupermarket.backsystem.modular.weixin.entity.WxTokenInfo;
import com.sxfq.loansupermarket.backsystem.modular.weixin.service.IWxService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.modular.weixin.config.SignUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.service.ISendMessageService;

@Service
@Transactional
public class IntegralMallLoginServiceImpl implements IntegralMallLoginService {
    @Autowired
    private IWxService wxService;

    @Autowired
    private ISendMessageService sendMessageService;

    @Autowired
    private IGuestDimensionService guestDimensionService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    WebSocketWxChat webSocketWxChat;

    @Autowired
    private SqlMapper sqlMapper;

    protected final static Logger log = LoggerFactory.getLogger(GunsApplication.class);
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAIQMzfyJwlbjuU";

    static final String accessKeySecret = "8yCe7fywBbBkZbMS8dXkS2tZpELT6N";

    public int generateQrCode(String id, String code) {
        wxService.getOpenid(code);
        String sql = "select reservations_id from members_user where open_id='" + ShiroKit.getSessionAttr("openid") + "' limit 1";
        WechatUserInfoEntity userInfo = sendMessageService.getSNSUserInfo(ShiroKit.getSessionAttr("openid"));
        MembersUser membersUser = sqlMapper.selectOne(sql, MembersUser.class);
        if (membersUser == null) {
            String insql = "insert into members_user (reservations_id,nickname,headimgurl,open_id,account,name,password,phone,medical_record_number,address,money_balance,abbreviation,sex,age) " +
                    " select reservations_id,'" + userInfo.getNickname() + "','" + userInfo.getHeadimgurl() + "','" + ShiroKit.getSessionAttr("openid") + "',customer_phone,customer_name,123,customer_phone,medical_record_number,address,money_balance,'" + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"" + "',customer_sex,customer_age " +
                    " from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"customer_info",0) + " where id='" + id + "';";
            return sqlMapper.insert(insql);
        } else {
            return 0;
        }
    }

    public int satisfactionSurveyAdd(SatisfactionSurvey ss) {
        String sql1 = "select * from members_user where open_id='" + ss.getOpenid() + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(sql1, MembersUser.class);

        String sqls11 = "select * from satisfaction_survey " +
                "where reservations_id='" + membersUser.getReservationsId() + "' and left(addTime,10)='" + DateTimeKit.now().substring(0, 10) + "' ";
        List<SatisfactionSurvey> ss1 = sqlMapper.selectList(sqls11, SatisfactionSurvey.class);  //今天评价过不能再提交
        if (ss1.size() == 0) {
            String sqls1 = "select * from satisfaction_survey where reservations_id='" + membersUser.getReservationsId() + "' limit 1";
            SatisfactionSurvey satisfactionSurvey = sqlMapper.selectOne(sqls1, SatisfactionSurvey.class);
            if (satisfactionSurvey == null) {   //首次参与问卷调查获得500积分
                String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                        " select reservations_id,name,phone," +
                        " (select points from get_points_settings_info where type_num=3),'任务积分','首次参与问卷调查获得积分'," +
                        " '系统','会员店' " +
                        " from members_user where open_id='" + ss.getOpenid() + "'";
                sqlMapper.insert(inupsql);
            } else {  //后期再次参与获得200积分
                String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                        " select reservations_id,name,phone," +
                        " (select points from get_points_settings_info where type_num=4),'任务积分','后期再次参与问卷调查获得积分'," +
                        " '系统','会员店' " +
                        " from members_user where open_id='" + ss.getOpenid() + "'";
                sqlMapper.insert(inupsql);
            }

            String evaluationOneList = ss.getEvaluationOneList().replace("[", "").replace("]", "").replace("\"", "");
            String evaluationTwoList = ss.getEvaluationTwoList().replace("[", "").replace("]", "").replace("\"", "");
            String sql = "insert into satisfaction_survey(reservations_id,customer_phone,customer_name,starlevel,proposal," +
                    "evaluationOneList,evaluationTwoList,addTime,abbreviation,case_id)" +
                    "values ('" + membersUser.getReservationsId() + "','" + membersUser.getPhone() + "','" + membersUser.getName()
                    + "','" + ss.getValue() + "','" + ss.getProposal() + "','" + evaluationOneList + "','" + evaluationTwoList + "','" + DateTimeKit.now()
                    + "','" + membersUser.getAbbreviation() + "','" + ss.getCaseid() + "')";
            return sqlMapper.insert(sql);
        }
        return 1;
    }

    public int activityLevelAdd(String openId, String score, String id) {
        String sql1 = "select * from members_user where open_id='" + openId + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(sql1, MembersUser.class);
        if (("积分").equals(score.substring(0, 2))) {   //积分
            String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                    " select reservations_id,name,phone," +
                    " '" + score.replace("积分", "") + "','活跃度积分','活跃度获得积分'," +
                    " '系统','会员店' " +
                    " from members_user where reservations_id='" + membersUser.getReservationsId() + "'";
            sqlMapper.insert(inupsql);
        } else {  //返现
            String inupsql = "insert into return_cash_info (reservations_id,customer_name,customer_phone,score_balance," +
                    "mode,remarks,add_people,add_time,add_store) " +
                    " select reservations_id,name,phone," +
                    " '" + score.replace("返现", "") + "','活跃度返现','活跃度获得返现'," +
                    " '系统','" + DateTimeKit.now() + "','会员店' " +
                    " from members_user where reservations_id='" + membersUser.getReservationsId() + "'";
            sqlMapper.insert(inupsql);
        }
        String sql = "update activity_level set mode=2 where id='" + id + "'";
        return sqlMapper.update(sql);
    }

    public void checkToken(HttpServletRequest request, HttpServletResponse response) {
        //token验证代码段
        try {
            log.info("请求已到达，开始校验token");
            if (org.apache.commons.lang3.StringUtils.isNotBlank(request.getParameter("signature"))) {
                String signature = request.getParameter("signature");
                String timestamp = request.getParameter("timestamp");
                String nonce = request.getParameter("nonce");
                String echostr = request.getParameter("echostr");
                log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);
                if (SignUtil.checkSignature(signature, timestamp, nonce)) {
                    log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
                    response.getOutputStream().println(echostr);
                }
            }
        } catch (IOException e) {
            log.error("校验出错");
            e.printStackTrace();
        }
    }

    public Map<String, String> createMembersUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();
        // 遍历所有子节点
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        // 释放资源
        inputStream.close();
        inputStream = null;
        System.out.print(map.get("Event"));
        if ("unsubscribe".equals(map.get("Event"))) {
            String upsql = "delete from open_info where open_id='" + map.get("FromUserName") + "'";
            sqlMapper.update(upsql);
        }
        if (ShiroKit.getSessionAttr("initial_push_content") == null) {
            String selSql1 = "select push_content from initial_push_info limit 1;";
            InitialPushInfo initialPushInfo = sqlMapper.selectOne(selSql1, InitialPushInfo.class);
            ShiroKit.setSessionAttr("initial_push_content", initialPushInfo.getPushContent());
        }
        if ("subscribe".equals(map.get("Event"))) {
            if (StringUtil.isNotEmpty(map.get("FromUserName"))) {
                String ssql = "select id from open_info a where open_id='" + map.get("FromUserName") + "' limit 1";
                QueryInfo queryInfo = sqlMapper.selectOne(ssql, QueryInfo.class);
                if (queryInfo == null) {
                    String inssql = "INSERT INTO `open_info` (`open_id`) VALUES ('" + map.get("FromUserName") + "');";
                    sqlMapper.insert(inssql);
                }
                String sql = "select reservations_id,update_time from members_user where open_id='" + map.get("FromUserName") + "' limit 1";
                MembersUser membersUser = sqlMapper.selectOne(sql, MembersUser.class);
                MembersUser membersUserInfo = guestDimensionService.getWxUserInfo(map.get("FromUserName"));
                if (membersUser != null) {
                    String upsql = "update members_user a set a.open_id = null , headimgurl = null where open_id='" + map.get("FromUserName") + "'";
                    sqlMapper.update(upsql);
                    String upsql1 = "update members_user a set a.open_id='" + map.get("FromUserName") + "', headimgurl='" + membersUserInfo.getHeadimgurl() + "'," +
                            "update_time=now(),update_times='" + membersUser.getUpdateTime() + "',yreservations_id='" + membersUser.getReservationsId() + "' where ticket='" + map.get("Ticket") + "'";
                    sqlMapper.update(upsql1);
                } else {
                    String upsql1 = "update members_user a set a.open_id='" + map.get("FromUserName") + "', headimgurl='" + membersUserInfo.getHeadimgurl() + "'," +
                            "update_time=now() where ticket='" + map.get("Ticket") + "'";
                    sqlMapper.update(upsql1);
                    String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                            " select reservations_id,name,phone," +
                            " (select points from get_points_settings_info where type_num=2),'任务积分','关注公众号获得积分'," +
                            " '系统','会员店' " +
                            " from members_user where ticket='" + map.get("Ticket") + "'";
                    sqlMapper.insert(inupsql);
                }
            }
            sendMessageService.sendTextMessage(ShiroKit.getSessionAttr("initial_push_content"), map.get("FromUserName"));
        }
        if ("SCAN".equals(map.get("Event"))) {
            if (StringUtil.isNotEmpty(map.get("FromUserName"))) {
                String ssql = "select id from open_info a where open_id='" + map.get("FromUserName") + "' limit 1";
                QueryInfo queryInfo = sqlMapper.selectOne(ssql, QueryInfo.class);
                if (queryInfo == null) {
                    String inssql = "INSERT INTO `open_info` (`open_id`) VALUES ('" + map.get("FromUserName") + "');";
                    sqlMapper.insert(inssql);
                }
                String sql = "select reservations_id from members_user where open_id='" + map.get("FromUserName") + "' limit 1";
                MembersUser membersUser = sqlMapper.selectOne(sql, MembersUser.class);
                MembersUser membersUserInfo = guestDimensionService.getWxUserInfo(map.get("FromUserName"));
                if (membersUser == null) {
                    String upsql = "update members_user a set a.open_id='" + map.get("FromUserName") + "', headimgurl='" + membersUserInfo.getHeadimgurl() + "'," +
                            "update_time=now() where ticket='" + map.get("Ticket") + "'";
                    sqlMapper.update(upsql);
                    String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                            " select reservations_id,name,phone," +
                            " (select points from get_points_settings_info where type_num=2),'任务积分','关注公众号获得积分'," +
                            " '系统','会员店' " +
                            " from members_user where ticket='" + map.get("Ticket") + "'";
                    sqlMapper.insert(inupsql);
                } else {
                    String upsql = "update members_user a set a.update_time=now(), headimgurl='" + membersUserInfo.getHeadimgurl() + "' where open_id='" + map.get("FromUserName") + "'";
                    sqlMapper.update(upsql);
                }
            }
            sendMessageService.sendTextMessage(ShiroKit.getSessionAttr("initial_push_content"), map.get("FromUserName"));
        }
        if (!"".equals(map.get("Content")) && !"null".equals(map.get("Content")) && map.get("Content") != null) {
            //根据关键字 查询 关键字所在的ID  返回ID中所回复的内容
            String selSql = "select id, content,type from official_account where keyword = '" + map.get("Content") + "' limit 1;";
            OfficialAccountInfo officialAccountInfo = sqlMapper.selectOne(selSql, OfficialAccountInfo.class);
            if (officialAccountInfo != null) {
                if ((officialAccountInfo.getType() == 1)) {//文本类型
                    sendMessageService.sendTextMessage(officialAccountInfo.getContent(), map.get("FromUserName"));
                }
                if ((officialAccountInfo.getType() == 2)) {//图片类型
                    sendMessageService.sendImageMessage(officialAccountInfo.getContent(), map.get("FromUserName"));
                }
            } else {
                String ssql = "select id from wx_chat_record a where a.sender='" + map.get("FromUserName") + "' and left(send_time,10)=left(now(),10) limit 1;";
                QueryInfo queryInfo = sqlMapper.selectOne(ssql, QueryInfo.class);
                if (queryInfo == null) {
                    sendMessageService.sendTextMessage(ShiroKit.getSessionAttr("initial_push_content"), map.get("FromUserName"));
                    GuestDimensionInfo guestDimensionInfo = new GuestDimensionInfo();
                    guestDimensionInfo.setOpenId(map.get("FromUserName")); // 发送方帐号（open_id）
                    guestDimensionInfo.setChatRecord(map.get("Content"));  // 消息内容
                    guestDimensionInfo.setMsgType(map.get("MsgType"));
                    guestDimensionInfo.setSender(map.get("FromUserName"));
                    guestDimensionInfo.setReceiver(map.get("ToUserName")); // 公众帐号
                    guestDimensionInfo.setSendStatus(1);
                    guestDimensionInfo.setIsNew(1);
                    guestDimensionService.insertWxChatRecord(guestDimensionInfo);
                    String selSql1 = "select open_id from initial_open_id;";
                    List<InitialPushInfo> initialPushInfoList = sqlMapper.selectList(selSql1, InitialPushInfo.class);
                    for (InitialPushInfo initialPushInfo : initialPushInfoList) {
                        sendMessageService.sendTextMessage("患者向湖北咿呀公众号发送了新消息！", initialPushInfo.getOpenId());
                    }
                    webSocketWxChat.sendMessageWxChat("收到" + map.get("FromUserName") + "的消息！");
                } else {
                    GuestDimensionInfo guestDimensionInfo = new GuestDimensionInfo();
                    guestDimensionInfo.setOpenId(map.get("FromUserName")); // 发送方帐号（open_id）
                    guestDimensionInfo.setChatRecord(map.get("Content"));  // 消息内容
                    guestDimensionInfo.setMsgType(map.get("MsgType"));
                    guestDimensionInfo.setSender(map.get("FromUserName"));
                    guestDimensionInfo.setReceiver(map.get("ToUserName")); // 公众帐号
                    guestDimensionInfo.setSendStatus(1);
                    guestDimensionInfo.setIsNew(1);
                    guestDimensionService.insertWxChatRecord(guestDimensionInfo);
                    String selSql1 = "select open_id from initial_open_id;";
                    List<InitialPushInfo> initialPushInfoList = sqlMapper.selectList(selSql1, InitialPushInfo.class);
                    for (InitialPushInfo initialPushInfo : initialPushInfoList) {
                        sendMessageService.sendTextMessage("患者向湖北咿呀公众号发送了新消息！", initialPushInfo.getOpenId());
                    }
                    webSocketWxChat.sendMessageWxChat("收到" + map.get("FromUserName") + "的消息！");
                }//o59Y2s5vQ9xwm2T7wBoUCRjyaCA4 o59Y2s8E7ae9Zov3Niq-fbY_CDeo
            }
        }
        return map;
    }

    public com.alibaba.fastjson.JSONObject getMedia_list() {
        String access_token = getAccessToken();
        SendMessageInfo sendMessageInfo = new SendMessageInfo();
        String sql = "select media_type,offset,count from media_type_info limit 1";
        QueryInfo queryInfo = sqlMapper.selectOne(sql, QueryInfo.class);
        sendMessageInfo.setType(queryInfo.getMediaType());
        sendMessageInfo.setOffset(queryInfo.getOffset());
        sendMessageInfo.setCount(queryInfo.getCount());
        String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + access_token;
        String jsonString = JSONObject.fromObject(sendMessageInfo).toString().replace("day", "Day");
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(url, "POST", jsonString);
        System.out.println(jsonObject);
        return jsonObject;
    }

    public String getPermanent_media_url() {
        String access_token = getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=" + access_token;
        String sql = "select media_id from media_type_info limit 1";
        QueryInfo queryInfo = sqlMapper.selectOne(sql, QueryInfo.class);
        Map map = new HashMap();
        map.put("media_id", queryInfo.getMediaId());
        String s = JSON.toJSONString(map);
        String jsonString = JSONObject.fromObject(s).toString().replace("day", "Day");
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(url, "POST", jsonString);
        String webMessageUrl = "";
        String back = String.valueOf(jsonObject.get("news_item"));
        back = back.substring(1, back.length() - 1);
        net.sf.json.JSONObject resultJSON1 = net.sf.json.JSONObject.fromObject(back);
        if (resultJSON1.get("url") != null) {
            webMessageUrl = resultJSON1.getString("url");
            System.out.println(webMessageUrl);
        }
        return webMessageUrl;
    }

    /**
     * 获取JSTicket
     */
    public String getJsapi_ticket() {
        String access_token = getAccessToken();
        String URL = ("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi").replace("ACCESS_TOKEN", access_token);
        com.alibaba.fastjson.JSONObject jsonObject = WebChatUtil.httpRequest(URL, "GET", null);//发送请求
        // 如果请求成功
        if (null != jsonObject) {
            return jsonObject.getString("ticket");
        } else {
            return "";
        }
    }

    public Map<String, String> getJsapiSign(String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + getJsapi_ticket() +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ret.put("url", url);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId", redisTemplate.opsForList().index("APPID",0)+"");
        return ret;
    }

    private String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public void getCmdOutput(String[] cmd) {
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
//            BufferedReader br = new BufferedReader(new InputStreamReader(runtime.exec(cmd).getInputStream()));
            process = runtime.exec("python C:\\Users\\174505131\\Desktop\\add.py 1 2");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String charsetName = "GB2312";
        InputStreamReader reader;
        try {
            reader = new InputStreamReader(process.getInputStream(), charsetName);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        BufferedReader bufferedReader = new BufferedReader(reader);
        String line;
        try {
            while (true) {
                line = bufferedReader.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String getAccessToken() {
        String accessToken = "";
        String getTokenSql = "select access_token as accessToken from wx_parameter_info where app_id='" + redisTemplate.opsForList().index("APPID",0)+"" + "' limit 1";
        WxTokenInfo wxTokenInfo = sqlMapper.selectOne(getTokenSql, WxTokenInfo.class);
        if (wxTokenInfo == null) {
            accessToken = WebChatConfig.getToken(redisTemplate.opsForList().index("APPID",0)+"",redisTemplate.opsForList().index("AppSecret",0)+"").getAccessToken();
            String updTokenSql = "update wx_parameter_info set access_token='" + accessToken + "' where app_id='" + redisTemplate.opsForList().index("APPID",0)+"" + "';";
            sqlMapper.update(updTokenSql);
        } else {
            if ("".equals(wxTokenInfo.getAccessToken()) || "null".equals(wxTokenInfo.getAccessToken())) {
                accessToken = WebChatConfig.getToken(redisTemplate.opsForList().index("APPID",0)+"",redisTemplate.opsForList().index("AppSecret",0)+"").getAccessToken();
                String updTokenSql = "update wx_parameter_info set access_token='" + accessToken + "' where app_id='" + redisTemplate.opsForList().index("APPID",0)+"" + "';";
                sqlMapper.update(updTokenSql);
            }
            accessToken = wxTokenInfo.getAccessToken();
        }
        return accessToken;
    }

    public int loginTo(String userName) {
        String sqls = "select a.* from members_user a where a.account='" + userName + "' limit 1";
        MembersUser membersUsers = sqlMapper.selectOne(sqls, MembersUser.class);
        if (membersUsers == null) {
            insertm(userName);
        }
        String sql = "select a.* from members_user a where a.account='" + userName + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(sql, MembersUser.class);
        String scsql = "select if(sum(b.score_balance) is null,0,sum(b.score_balance)) as scoreBalance " +
                " from score_deal b " +
                " where b.reservations_id='" + membersUser.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(scsql, MembersUser.class);
        String resql = "select if(sum(b.actual_account_balance) is null,0,sum(b.actual_account_balance)) as actualAccountBalance " +
                " from reservemoney_deal b " +
                " where b.reservations_id='" + membersUser.getReservationsId() + "' limit 1";
        MembersUser membersUser2 = sqlMapper.selectOne(resql, MembersUser.class);
        membersUser.setScoreBalance(membersUser1.getScoreBalance());
        membersUser.setActualAccountBalance(membersUser2.getActualAccountBalance());
        if (StringUtils.isNotEmpty(membersUser.getReservationsId())) {
            String sql2 = "update members_user a set a.open_id='" + ShiroKit.getSessionAttr("openid") + "' ,update_times=now() where account='" + userName + "'";
            sqlMapper.update(sql2);
            String sqlk = "select * from score_deal where reservations_id='" + membersUser.getReservationsId() + "'" +
                    " and remarks='关注公众号获得积分' limit 1 ";
            MembersUser mi = sqlMapper.selectOne(sqlk, MembersUser.class);
            if (mi == null) {
                String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                        " select reservations_id,name,phone," +
                        "(select points from get_points_settings_info where type_num=2)," +
                        "'任务积分','关注公众号获得积分'," +
                        "'系统','会员店' " +
                        "from members_user where reservations_id='" + membersUser.getReservationsId() + "'";
                sqlMapper.insert(inupsql);
            }
            String ssql = "select id from open_info a where open_id='" + ShiroKit.getSessionAttr("openid") + "' limit 1";
            QueryInfo queryInfo = sqlMapper.selectOne(ssql, QueryInfo.class);
            if (queryInfo == null) {
                String inssql = "INSERT INTO `open_info` (`open_id`) VALUES ('" + ShiroKit.getSessionAttr("openid") + "');";
                sqlMapper.insert(inssql);
            }
            ShiroKit.setSessionAttr("reservationsId", membersUser.getReservationsId());
            return 1;
        } else {
            String sql2 = "select * from distinction_customer_status a where a.customer_phone='" + userName + "' and status=1 limit 1";
            CustomerInfo cinfo = sqlMapper.selectOne(sql2, CustomerInfo.class);
            if (cinfo != null) {
                String sql3 = "select * from " + cinfo.getAbbreviation() + "customer_info a where a.reservations_id='" + cinfo.getReservationsId() + "'" +
                        " order by a.arrival_time desc limit 1";
                CustomerInfo cinfo2 = sqlMapper.selectOne(sql3, CustomerInfo.class);
                String sqlb = "select * from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) + " a where a.num=1 limit 1";
                VipLevelInfo vip = sqlMapper.selectOne(sqlb, VipLevelInfo.class);
                String openid = ShiroKit.getSessionAttr("openid");
                String birthday;
                if (cinfo2.getBirthday() == null || cinfo2.getBirthday() == "") {
                    birthday = "null";
                } else {
                    birthday = "'" + cinfo2.getBirthday() + "'";
                }
                WechatUserInfoEntity userInfoEntity = sendMessageService.getSNSUserInfo(openid);
                String sqlm = "insert into members_user (`reservations_id`,nickname,headimgurl,open_id,`account`, `name`, `password`, `birthday`, `sex`, `age`, `phone`, " +
                        "`vip_level_name`, `vipLevel_Id`, `earnest_balance`, `money_balance`, `medical_record_number`, `email`," +
                        "`abbreviation`, `address`) values ('" + cinfo2.getReservationsId() + "','" + userInfoEntity.getNickname() + "','" + userInfoEntity.getHeadimgurl() + "','" + openid + "','" + cinfo2.getCustomerPhone() + "'," +
                        "'" + cinfo2.getCustomerName() + "','123'," + birthday + "," + cinfo2.getCustomerSex() + "," + cinfo2.getCustomerAge() + "," +
                        "'" + cinfo2.getCustomerPhone() + "','" + vip.getVipLevelName() + "','" + vip.getNum() + "'," +
                        "'" + cinfo2.getMoneyBalance() + "','" + cinfo2.getJfbalance() + "','" + cinfo2.getMedicalRecordNumber() + "'," +
                        "'" + cinfo2.getEmail() + "','" + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"" + "','" + cinfo2.getAddress() + "')";
                sqlMapper.insert(sqlm);
                ShiroKit.setSessionAttr("reservationsId", cinfo2.getReservationsId());
                return 2;
            } else {
                return 3;
            }
        }
    }

    public void insertm(String userName) {
        String selesql = "select * from distinction_customer_status where customer_phone='" + userName + "' and status=1 limit 1";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(selesql, ConsultantInfo.class);
        if (consultantInfo != null) {
            String insql = "insert into members_user (reservations_id,account,name,password,phone,medical_record_number,address,money_balance,abbreviation,sex,age) " +
                    " select reservations_id,'" + consultantInfo.getCustomerPhone() + "',customer_name,123,customer_phone,medical_record_number,address,money_balance,'" + consultantInfo.getAbbreviation() + "',customer_sex,customer_age " +
                    " from " + consultantInfo.getAbbreviation() + "customer_info where reservations_id='" + consultantInfo.getReservationsId() + "' limit 1;";
            sqlMapper.insert(insql);
        }
    }

    public MembersUser getPersonalCenter(String code) {
        String openId = wxService.getOpenid(code);
        MembersUser membersUser = null;
        String reservationsId = ShiroKit.getSessionAttr("reservationsId");
        if (StringUtils.isBlank(reservationsId)) {
            return membersUser;
        }
        String sql = "select a.* from members_user a where a.reservations_id='" + reservationsId + "' limit 1";
        membersUser = sqlMapper.selectOne(sql, MembersUser.class);
        String scsql = "select if(sum(b.score_balance) is null,0,sum(b.score_balance)) as scoreBalance " +
                " from score_deal b " +
                " where b.reservations_id='" + reservationsId + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(scsql, MembersUser.class);
        String resql = "select if(sum(b.actual_account_balance) is null,0,sum(b.actual_account_balance)) as actualAccountBalance " +
                " from reservemoney_deal b " +
                " where b.reservations_id='" + reservationsId + "' limit 1";
        MembersUser membersUser2 = sqlMapper.selectOne(resql, MembersUser.class);
        String recsql = "select if(sum(b.score_balance) is null,0,sum(b.score_balance)) as scoreBalancex " +
                " from return_cash_info b " +
                " where b.reservations_id='" + reservationsId + "' limit 1";
        MembersUser membersUser3 = sqlMapper.selectOne(recsql, MembersUser.class);
        membersUser.setScoreBalancex(membersUser3.getScoreBalancex());
        membersUser.setScoreBalance(membersUser1.getScoreBalance());
        membersUser.setActualAccountBalance(membersUser2.getActualAccountBalance());
        membersUser.setReservationsId(reservationsId);
        membersUser.setOpenId(openId);
        return membersUser;
    }

    public MembersUser getActivityLevel(String code) {
        String openId = wxService.getOpenid(code);
        MembersUser membersUser = null;
        String reservationsId = ShiroKit.getSessionAttr("reservationsId");
        if (StringUtils.isBlank(reservationsId)) {
            return membersUser;
        }
        String sql = "select open_id as openId,id,(select points from get_points_settings_info where type_num=10)*a.percentage as score,\n" +
                "((select points from get_points_settings_info where type_num=10)*a.percentage)" +
                "/100 as moey " +
                "from activity_level a where a.reservations_id='" + reservationsId + "' and a.mode=1 limit 1";
        membersUser = sqlMapper.selectOne(sql, MembersUser.class);
        return membersUser;
    }

    public int shareEarnPoints(String code) {
        String openId = wxService.getOpenid(code);
        String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                " select reservations_id,name,phone," +
                " (select points from get_points_settings_info where type_num=12),'任务积分','分享获得积分'," +
                " '系统','会员店' " +
                " from members_user where open_id='" + openId + "'";
        return sqlMapper.insert(inupsql);
    }

    public String verificationCode(String pid, String reservationsId, String verificationCode, String code) {
        if (verificationCode.equals(code) && reservationsId.equals(ShiroKit.getSessionAttr("reservationsId"))) {
            String strSql = "insert into point_conversion_info (product_id,reservations_id,code) " +
                    "values ('" + pid + "','" + reservationsId + "','" + code + "');";
            String upSql = "update point_reword_info a set a.conversioned_number=conversioned_number+1," +
                    "a.putaway_number=putaway_number-1 where id='" + pid + "';"; //减少商品上架的数量，减少会员的储值余额
            String productList = "select * from point_reword_info order by create_time desc ";
            List<PointRewordInfo> pointRewordInfoList = sqlMapper.selectList(productList, PointRewordInfo.class); //查询所有的商品列表
            for (PointRewordInfo pointRewordInfo : pointRewordInfoList) {
                String pointSql = "select id,product_id,image_path from point_reword_iconinfo where product_id='" + pointRewordInfo.getId() + "' limit 1";
                PointRewordInfo info = sqlMapper.selectOne(pointSql, PointRewordInfo.class);
                if (info != null) {
                    pointRewordInfo.setProductId(info.getProductId());
                    pointRewordInfo.setImagePath(info.getImagePath());
                }
            }
            String sql1 = "select a.* from members_user a where a.reservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' limit 1";
            MembersUser membersUser1 = sqlMapper.selectOne(sql1, MembersUser.class);
            // 插入到积分表中
            String insertSql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,add_people,add_store) values('" + reservationsId + "','" + membersUser1.getName() + "'," +
                    " '" + membersUser1.getPhone() + "',-(select product_price from point_reword_info where id='" + pid + "'),'退兑换积分','" + membersUser1.getName() + "','会员店')";
            sqlMapper.insert(insertSql);
            sqlMapper.insert(strSql);
            sqlMapper.update(upSql);
            return "ss";
        } else {
            return "aa";
        }
    }

    public MembersUser getScoreShopping(String code, String area) {
        wxService.getOpenid(code);
        if ("wh".equals(area)) {
            area = "yiya_wh";
        } else {
            area = "yiya_es";
        }
        MembersUser membersUser = new MembersUser();
        String reservationsId = ShiroKit.getSessionAttr("reservationsId");
        String productList = "select a.*,b.image_path as imagePath from point_reword_info a " +
                "left join point_reword_iconinfo b on a.id = b.product_id where b.mainFigure=1 and left(a.area,7)='" + area + "' order by number desc";
        List<PointRewordInfo> pointRewordInfoList = sqlMapper.selectList(productList, PointRewordInfo.class); //查询所有的商品列表
        if (StringUtils.isBlank(reservationsId)) {
            membersUser.setAccount("未登录");
            membersUser.setScoreBalance("0");
            membersUser.setReservationsId(null);
            membersUser.setListPointRewordInfo(pointRewordInfoList);
            return membersUser;
        }
        String sql = "select a.* from members_user a where a.reservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' limit 1";
        membersUser = sqlMapper.selectOne(sql, MembersUser.class);
        String scsql = "select if(sum(b.score_balance) is null,0,sum(b.score_balance)) as scoreBalance " +
                " from score_deal b " +
                " where b.reservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(scsql, MembersUser.class);
        String resql = "select if(sum(b.actual_account_balance) is null,0,sum(b.actual_account_balance)) as actualAccountBalance " +
                " from reservemoney_deal b " +
                " where b.reservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' limit 1";
        MembersUser membersUser2 = sqlMapper.selectOne(resql, MembersUser.class);
        membersUser.setScoreBalance(membersUser1.getScoreBalance());
        membersUser.setActualAccountBalance(membersUser2.getActualAccountBalance());
        membersUser.setReservationsId(reservationsId);
        membersUser.setListPointRewordInfo(pointRewordInfoList);
        return membersUser;
    }

    public String codeNumber(String code, String codeValue, String id) {
        if (!codeValue.equals(code)) {
            return "1";
        } else {
            String selSql = "update point_conversion_info a set a.status='2' where id='" + id + "'";
            sqlMapper.update(selSql);
        }
        return "ss";
    }


    public Integer signInScore(String reservationsId) {
        String sql = "select * from score_deal where reservations_id='" + reservationsId + "'" +
                " and remarks like '%签到获得积分%' and left(add_time,10)='" + DateTimeKit.now().substring(0, 10) + "'";
        ScoreDealInfo sinfo = sqlMapper.selectOne(sql, ScoreDealInfo.class);
        if (sinfo == null) {
            String inupsql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,remarks,add_people,add_store)" +
                    " select reservations_id,name,phone," +
                    " (select points from get_points_settings_info where type_num=5),'任务积分','签到获得积分100'," +
                    " '系统','会员店' " +
                    " from members_user where reservations_id='" + reservationsId + "'";
            return sqlMapper.insert(inupsql);
        } else {
            return 2;
        }
    }

    public List<PointRewordInfo> PointRewordInfototal(String startCreateTime, String endCreateTime) {
        String contitionInfo = "";
        if (StringUtils.isNotBlank(startCreateTime)) {
            contitionInfo += " and t.create_time >='" + startCreateTime + "' ";
        }
        if (StringUtils.isNotBlank(endCreateTime)) {
            contitionInfo += " and t.create_time <='" + endCreateTime + "' ";
        }
        String sql = " select count(*) as countNum from (select t.id from  point_conversion_info t  where t.status ='1' " + contitionInfo + ") t" +

                " union all  select count(*) as countNum from (select t.id from  point_conversion_info t where t.status ='2' " + contitionInfo + ") t";

        List<PointRewordInfo> tongJiInfoList1 = sqlMapper.selectList(sql, PointRewordInfo.class);
        return tongJiInfoList1;
    }

    public List<CustomerInfo> getMedicalRecordsInfo(String code) {
        wxService.getOpenid(code);
        List<CustomerInfo> customerInfoList = null;
        String reservationsId = ShiroKit.getSessionAttr("reservationsId");
        if (StringUtils.isBlank(reservationsId)) {
            return customerInfoList;
        }
        //到过的店
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String customerTables = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            if (i == abbreviationList.size() - 1) {
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,10) as startTime," +
                        "left(t.end_time,19) as endTime, substring(t.start_time,11,6) as startTimes, substring(t.end_time,11,6) as endTimes,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' ";
            } else {
                customerTables += "select customer_name as customerName, left(t.create_appointment_time,19) as createAppointmentTime,left(t.start_time,10) as startTime," +
                        "left(t.end_time,19) as endTime, substring(t.start_time,11,6) as startTimes, substring(t.end_time,11,6) as endTimes,t.id as id,t.remarks_reservation as remarksReservation," +
                        "t.reservations_id as reservationsId,t.doctor as doctor,t.field_tc as fieldTc,t.remarks as remarks,t.arrival_status as arrivalStatus," +
                        "t.archiving as archiving,t.arrival_store as arrivalStore,t.customer_status as customerStatus,t.status as status," +
                        "t.appointment_pay_service as appointmentPayService " +
                        "from " + head + "customer_info t where reservations_id='" + reservationsId + "' union ";
            }
        }
        //就诊记录
        String sql11 = "select * from (" + customerTables + ") t order by t.startTime desc";
        return sqlMapper.selectList(sql11, CustomerInfo.class);
    }

    public MemberRecommendationInfo getMemberRecommendation(String code) {
        String sql = "select a.id,a.recommendation_name as recommendationName,a.recommendation_phone as recommendationPhone," +
                "left(a.time,10) as startTimes,right(a.time,8) as endTimes from crmscs.member_recommendation_list_info a where open_id='" + ShiroKit.getSessionAttr("openid") + "';";
        MemberRecommendationInfo memberRecommendation = sqlMapper.selectOne(sql, MemberRecommendationInfo.class);
        return memberRecommendation;
    }

    public int sureRecommendation(String recommendationName, String recommendationPhone) {
        String sesql = "select reservations_id from distinction_customer_status a " +
                "where customer_phone like CONCAT('%','" + recommendationPhone + "','%') and customer_name='" + recommendationName + "' limit 1;";
        QueryInfo queryInfo = sqlMapper.selectOne(sesql, QueryInfo.class);
        if (queryInfo == null) {
            return 0;
        } else {
            if (queryInfo.getReservationsId().equals(ShiroKit.getSessionAttr("reservationsId"))) {
                return 1;
            } else {
                String sesql1 = "select id from member_recommendation_list_info a " +
                        "where treservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' and reservations_id='" + queryInfo.getReservationsId() + "' limit 1;";
                QueryInfo queryInfo1 = sqlMapper.selectOne(sesql1, QueryInfo.class);
                if (queryInfo1 == null) {
                    String sql = "INSERT INTO `member_recommendation_list_info` ( `reservations_id`,`treservations_id`, `open_id`, `recommendation_name`, `recommendation_phone`)" +
                            " VALUES ('" + ShiroKit.getSessionAttr("reservationsId") + "','" + queryInfo.getReservationsId() + "','" + ShiroKit.getSessionAttr("openid") + "', '" + recommendationName + "', '" + recommendationPhone + "');";
                    sqlMapper.insert(sql);
                    String insql = "INSERT INTO score_deal (`reservations_id`, `customer_name`, `customer_phone`, `score_balance`, `mode`, `remarks`, `add_people`,`add_store`)" +
                            " VALUES ('" + queryInfo.getReservationsId() + "', '" + recommendationName + "', '" + recommendationPhone + "'" +
                            ",(select points from get_points_settings_info where type_num=1), '任务积分', '绑定推荐人获得积分', '系统', '会员店')";
                    sqlMapper.insert(insql);
                    return 3;
                } else {
                    return 2;
                }
            }
        }
    }

    public String getBackIntegral(String id, String reservationId) {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            return "9";
        } else {
            String selstr = "select * from point_conversion_info where id='" + id + "' limit 1";
            PointRewordInfo info1 = sqlMapper.selectOne(selstr, PointRewordInfo.class);
            String sqlStr = "select * from score_deal where reservations_id='" + reservationId + "' limit 1";
            ScoreDealInfo info = sqlMapper.selectOne(sqlStr, ScoreDealInfo.class);
            //退还到商品表中
            String jifenSql = "select id,product_price,putaway_number,conversioned_number,surplus_number from point_reword_info where id='" + info1.getProductId() + "' limit 1;";
            PointRewordInfo pointRewordInfo = sqlMapper.selectOne(jifenSql, PointRewordInfo.class);
            String upsql = "update point_reword_info a set a.putaway_number=putaway_number+" + info1.getNumAcount() + ",a.conversioned_number=conversioned_number-" + info1.getNumAcount() + " where id='" + info1.getProductId() + "';";
            // 插入到积分表中
            int a = pointRewordInfo.getProductPrice() * info1.getNumAcount();
            String insertSql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,add_people,add_store,remarks) values('" + info.getReservationsId() + "','" + info.getCustomerName() + "'," +
                    " '" + info.getCustomerPhone() + "','" + a + "','退积分','" + info.getCustomerName() + "','会员店','退积分')";
            //删除兑换记录
            String deleteSql = "delete from point_conversion_info where id='" + id + "'";
            sqlMapper.insert(insertSql);
            sqlMapper.update(upsql);
            sqlMapper.delete(deleteSql);
            return "ss";
        }
    }

    public MembersUser getMembershipCard(String membersNum, String phone) {
        String sqlm = "select a.reservations_id as reservationsId, b.vip_level_name as vipLevelName,(b.discount_discount*10) as discountDiscount,phone " +
                " from members_user a left join " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"vip_level_info",0) + " b on (a.vip_level_name=b.vip_level_name) where members_num='" + membersNum + "' and phone='" + phone + "' limit 1;";
        MembersUser membersUser = sqlMapper.selectOne(sqlm, MembersUser.class);
        if (membersUser == null) {
            return null;
        }
        String getMoneyBalance = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='" + membersUser.getReservationsId() + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(getMoneyBalance, MembersUser.class);
        String jfbalancesql = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info " +
                "where reservations_id='" + membersUser.getReservationsId() + "' limit 1";
        ScoreDealInfo scoreDealInfo = sqlMapper.selectOne(jfbalancesql, ScoreDealInfo.class);
        membersUser.setMoneyBalancex(membersUser1.getMoneyBalance());
        membersUser.setScoreBalancex(scoreDealInfo.getScoreBalance());
        return membersUser;
    }

    public int codeSend(String code, String codeValues, String openId, String customerPhone) {
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        String reservationsId = CommUtils.getUUID() + randomNumber;
        String selPhoneSql = "select reservations_id,phone from members_user where phone='" + customerPhone + "'";
        List<MembersUser> membersUserList = sqlMapper.selectList(selPhoneSql, MembersUser.class);
        if (!codeValues.equals(code)) {
            return 0;
        } else {
            if (membersUserList.size() > 0) {
                return 1;
            } else {
                WechatUserInfoEntity userInfoEntity = sendMessageService.getSNSUserInfo(openId);
                String insertSql = "insert into members_user (reservations_id,nickname,headimgurl,account,name,password,phone,open_id) values" +
                        "('" + reservationsId + "','" + userInfoEntity.getNickname() + "','" + userInfoEntity.getHeadimgurl() + "','1','1','123','" + customerPhone + "','" + openId + "')";
                sqlMapper.insert(insertSql);
                return 2;
            }
        }
    }

    public String getConversion(String id, String reservationsId, int numAcount) throws ClientException, InterruptedException {
        if (ShiroKit.getSessionAttr("reservationsId") == null) {
            return "9";
        }
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        //查询会员信息
        String sql = "select a.* from members_user a where a.reservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(sql, MembersUser.class);
        String scsql = "select if(sum(b.score_balance) is null,0,sum(b.score_balance)) as scoreBalance " +
                " from score_deal b where b.reservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(scsql, MembersUser.class);
        String resql = "select if(sum(b.actual_account_balance) is null,0,sum(b.actual_account_balance)) as actualAccountBalance " +
                " from reservemoney_deal b where b.reservations_id='" + ShiroKit.getSessionAttr("reservationsId") + "' limit 1";
        MembersUser membersUser2 = sqlMapper.selectOne(resql, MembersUser.class);
        membersUser.setScoreBalance(membersUser1.getScoreBalance());
        membersUser.setActualAccountBalance(membersUser2.getActualAccountBalance());
        //查询商品信息
        String productSql = "select id,product_name,product_price,market_price,putaway_number,conversioned_number,surplus_number from point_reword_info where id='" + id + "' limit 1";
        PointRewordInfo PointRewordInfo = sqlMapper.selectOne(productSql, PointRewordInfo.class);
        String signName = "咿呀口腔";
        String phoneNumbers = membersUser.getPhone();
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumbers);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_173251028");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{ \"code\":\"" + code + "\"}");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("123");
        //发短信
        SendSmsResponse response = sendSms(request);
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());
        Thread.sleep(600L);
        String strSql = "insert into point_conversion_info (product_id,reservations_id,code,num_acount) " +
                "values ('" + id + "','" + reservationsId + "','" + code + "','" + numAcount + "');";
        String upSql = "update point_reword_info a set a.conversioned_number=conversioned_number+" + numAcount + "," +
                "a.putaway_number=putaway_number-" + numAcount + " where id='" + id + "';"; //减少商品上架的数量，增加已兑换的数量
        String productList = "select * from point_reword_info order by create_time desc ";
        List<PointRewordInfo> pointRewordInfoList = sqlMapper.selectList(productList, PointRewordInfo.class); //查询所有的商品列表
        for (PointRewordInfo pointRewordInfo : pointRewordInfoList) {
            String pointSql = "select id,product_id,image_path from point_reword_iconinfo where product_id='" + pointRewordInfo.getId() + "' limit 1";
            PointRewordInfo info = sqlMapper.selectOne(pointSql, PointRewordInfo.class);
            if (info != null) {
                pointRewordInfo.setProductId(info.getProductId());
                pointRewordInfo.setImagePath(info.getImagePath());
            }
        }
        // 插入到积分表中
        String a = "select id,product_price from point_reword_info where id='" + id + "'";
        PointRewordInfo info = sqlMapper.selectOne(a, PointRewordInfo.class);
        int cash = -info.getProductPrice() * (numAcount);
        String insertSql = "insert into score_deal (reservations_id,customer_name,customer_phone,score_balance,mode,add_people,add_store,remarks) values('" + reservationsId + "','" + membersUser.getName() + "'," +
                " '" + membersUser.getPhone() + "','" + cash + "','兑换积分','" + membersUser.getName() + "','会员店','积分兑换')";
        sqlMapper.insert(insertSql);
        sqlMapper.insert(strSql);
        sqlMapper.update(upSql);
        return id + "," + reservationsId + "," + code;
    }

    public static SendSmsResponse sendSms(SendSmsRequest request) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        return sendSmsResponse;
    }

    public static QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber("18602744660");
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);
        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);
        return querySendDetailsResponse;
    }

    public int getCode(String customerPhone) throws ClientException, InterruptedException {
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        String signName = "咿呀口腔";
        String phoneNumbers = customerPhone;
        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phoneNumbers);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_174989218");
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{ \"code\":\"" + code + "\"}");
        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("123");
        //发短信
        SendSmsResponse response = sendSms(request);
        System.out.println("短信接口返回的数据----------------");
        System.out.println("Code=" + response.getCode());
        System.out.println("Message=" + response.getMessage());
        System.out.println("RequestId=" + response.getRequestId());
        System.out.println("BizId=" + response.getBizId());
        Thread.sleep(600L);
        return code;
    }

    public int getCheckPrice(String id, String reservationsId, String productPrice) {
        int count = 0;
        int num = 0;
        String scsql = "select if(sum(b.score_balance) is null,0,sum(b.score_balance)) as scoreBalance " +
                " from score_deal b where b.reservations_id='" + reservationsId + "' limit 1";
        MembersUser membersUser1 = sqlMapper.selectOne(scsql, MembersUser.class);
        String productSql = "select id,product_name,product_price,market_price,putaway_number,conversioned_number,surplus_number from point_reword_info where id='" + id + "' limit 1";
        PointRewordInfo PointRewordInfo = sqlMapper.selectOne(productSql, PointRewordInfo.class);
        //本月已兑换的张数
        String curTime = DateTimeKit.now().substring(0, 7);
        String curNumSql = "select  sum(num_acount) as numTotal from (SELECT id,create_time as createTime,num_acount,reservations_id,product_id FROM " +
                "point_conversion_info WHERE product_id = '" + id + "' AND reservations_id = '" + reservationsId + "' ) t where t.product_id = '" + id + "' " +
                "AND t.reservations_id = '" + reservationsId + "' and left(t.createTime,7)='" + curTime + "' ";
        PointRewordInfo info = sqlMapper.selectOne(curNumSql, PointRewordInfo.class);
        if (info == null) {
            num = 0;
        }else{
            num = info.getNumTotal();
        }
        //库存不够
        if (PointRewordInfo.getPutawayNumber() <= 0) {
            return -1;
        }
        if (Double.parseDouble(membersUser1.getScoreBalance()) - Double.parseDouble(productPrice) < 0) {
            return -2;
        }
        Double a = Double.parseDouble(membersUser1.getScoreBalance());
        int b = (int) Math.floor(a / (Integer.parseInt(productPrice)));
        if (num > 10) {
            count = 0;
        } else {
            if (b > 10) {
                count = 10 - num;
            } else {
                if ((10 - num) > b) {
                    count = b;
                } else {
                    count = 10 - num;
                }
            }
        }
        return count;
    }

    public List<CaseInfo> getCaseDetails(String code) {
        wxService.getOpenid(code);
        List<CaseInfo> caseInfoList = new ArrayList<>();
        //病例记录
        //1、先查询当前客户的所有病例记录
        String caseInfoSql = "select left(t1.finnally_time,19) as finnallyTime1,t1.*,t2.name as customerName," +
                "  (CASE t2.sex  " +
                "  WHEN 1 THEN  " +
                "  '男'  " +
                "  WHEN 2 THEN  " +
                "  '女'  " +
                "  ELSE  " +
                "  '未知'  " +
                "  END  " +
                " ) as sex from case_info t1 " +
                "left join members_user t2 on t1.reservations_id=t2.reservations_id " +
                "where t2.open_id='" + ShiroKit.getSessionAttr("openid") + "' order by t1.finnally_time desc";
        caseInfoList = sqlMapper.selectList(caseInfoSql, CaseInfo.class);
        if (caseInfoList == null) {
            return caseInfoList;
        }
        for (CaseInfo infos : caseInfoList) {
            if (infos != null) {
                if (infos.getOperationTime() != "" && infos.getOperationTime() != null) {
                    infos.setOperationTime(infos.getOperationTime().substring(0, 10));
                }
            }
        }
        //2.循环遍历每个病例记录，给对应病例的牙位属性赋值
        for (CaseInfo caseInfo : caseInfoList) {
            String toothSIteSql = "select * from tooth_site t1 where t1.case_id='" + caseInfo.getId() + "' ";//然后查询牙位集合
            List<ToothSite> toothSiteList = sqlMapper.selectList(toothSIteSql, ToothSite.class);
            for (ToothSite toothSite : toothSiteList) {//根据对应的牙位类型，给病例实体的对应牙位属性赋值
                if ("1".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite1List().add(toothSite);
                }
                if ("2".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite2List().add(toothSite);
                }
                if ("3".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite3List().add(toothSite);
                }
                if ("4".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite4List().add(toothSite);
                }
                if ("5".equals(toothSite.getYaType())) {
                    caseInfo.getToothSite5List().add(toothSite);
                }
            }
        }
        return caseInfoList;
    }

}